function attval = h5attget(hfile,varname,attname)
%H5ATTGET  Retrieve attribute from HDF5 file.
% 
%   ATTVAL = H5ATTGET(HFILE,LOCATION,ATTNAME) retrieves an attribute named
%   ATTNAME from the HDF5 file HFILE.  LOCATION can be a group, a dataset,
%   or a named datatype.  Use '/' for the root group.
%
%   Scalar string attributes are reported as a row string, rather than a
%   column string.  Other string attributes are returned as-is.
% 
%   1D attributes are returned as a single row, rather than as a column.
% 
%   Example:  
%       d = h5attget('example.h5','/g1/g1.1/dset1.1.1','att1');
%
%   See also h5attput.

%   Copyright 2009-2010 The MathWorks, Inc.
%
%   Credit also to Philip Top (LLNL)

% Just use the defaults for now.
flags = 'H5F_ACC_RDONLY';
plist_id = 'H5P_DEFAULT';

% Allow for the user to pass the file ID directly.
if ischar(hfile)
    if ~exist(hfile,'file')
        error('unable to open file.');
    else
        file_id = H5F.open(hfile,flags,plist_id);
    end
else
    file_id = hfile;
end

parent_id = set_attribute_parent_id(file_id,varname);
attr_id = H5A.open_name( parent_id, attname);
attval = H5A.read(attr_id,'H5ML_DEFAULT');

% Read the datatype information and use that to possibly post-process
% the attribute data.
attr_datatype = H5A.get_type(attr_id);
attr_class = H5T.get_class(attr_datatype);

attr_space_id = H5A.get_space(attr_id);
ndims = H5S.get_simple_extent_dims(attr_space_id);

% Do we alter the size, shape of the attribute?
switch (attr_class)
    
    case H5ML.get_constant_value('H5T_STRING')
        % Is it a scalar attribute?
        if ( ndims == 0 )
            % Yep, it's a scalar.  Transpose it.
            attval = attval';
        end
        if (isa(attval,'cell'))
            if (length(attval)==1)
                attval=attval{1};
            end
        end
    case { H5ML.get_constant_value('H5T_INTEGER'), ...
            H5ML.get_constant_value('H5T_FLOAT') }
        if ( ndims == 1 )
            % If 1D, make it a row vector.
            attval = reshape(attval,1,numel(attval));
        end
        
    case H5ML.get_constant_value('H5T_COMPOUND')
        % Was this a complex attribute?
        if isfield(attval,'real') && isfield(attval,'imag') ...
                && (numel(fieldnames(attval)) == 2)
            attval = attval.real + 1j*attval.imag;
        end
end


% Close all the IDs.
H5T.close(attr_datatype);
H5A.close(attr_id);

close_attribute_parent_id(file_id,varname,parent_id);

% Only close the file ID if it was not already opened when we started.
if ischar(hfile)
    H5F.close(file_id);
end
